package com.nowcoder.community.controller;

import com.google.code.kaptcha.Producer;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;


import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {
    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private UserService userService;

    /*注入配置信息*/
    @Value("server.servlet.context-path")
    private  String contextPath;

    public static final Logger  logger= LoggerFactory.getLogger(LoginController.class);

    /**
     * 访问注册页面
     */
    @RequestMapping(path="/register",method = RequestMethod.GET)
    public String getRegisterPage(){
        return "/site/register";
    }

    /**
     * 提交注册数据
     */
    @RequestMapping(path="/register",method = RequestMethod.POST)
    public String register(Model model, User user){  //SpringMVC在调用方法时，将user自动传入model
        Map<String, Object> map = userService.register(user);
        //如果注册成功
        if(map == null || map.isEmpty()){
            //返回提示信息
            model.addAttribute("msg","注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活！");
            //返回目标跳转页面
            model.addAttribute("target","/index");
            return "site/operate-result";
        }else {
            //注册失败
            //返回错误信息
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("usernameMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return  "/site/register";
        }
    }

    /**
     * 激活账号
     */
    //http://localhost:8080/community/activation/101/code
    @RequestMapping(path ="/activation/{userId}/{code}",method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code") String code) {
        int result = userService.activation(userId, code);
        //根据激活情况的不同，返回不同的信息
        if (result == ACTIVATION_SUCCESS) {
            //激活成功
            model.addAttribute("msg", "激活成功，你的账号可以正常使用");
            model.addAttribute("target", "/index");
        } else if (result == ACTIVATION_REPEAT) {
            //重复激活
            model.addAttribute("msg", "无效操作，账号已经被激活过");
            model.addAttribute("target", "/indez");
        } else {
            model.addAttribute("msg", "激活失败，您提供的激活码不正确");
            model.addAttribute("target", "/indez");
        }
        return "site/operate-result";
    }

    /**
     * 访问登陆页面
     */
    @RequestMapping(path="/login",method = RequestMethod.GET)
    public String getLoginPage(){
        return "/site/login";
    }

    /**
     * 生成随机字符图片
     * @param response
     * @param session
     */
    @RequestMapping(path="/kaptcha",method = RequestMethod.GET)
    //因为返回的是图片，Java没有这个数据类型，在HttpResponse对象中手动添加，所以返回void
    //生成完验证码，服务端需要把它记住，当你登录再次访问服务器的时候，从而验证验证码是否正确
    //验证码不能放在客户端，否则敏感数据很容易被盗取，因此放在服务端，跨请求使用session
    public void getKaptcha(HttpServletResponse response, HttpSession session){  //注意response和session的版本，不能使用javax
        //生成验证码：需要注入相关配置类的bean
        String text = kaptchaProducer.createText();
        //生成验证码对应的图片
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入session
        session.setAttribute("kaptcha",text);

        //将图片输出给浏览器，通过response对象输出
        //1.设置相应内容的类型
        response.setContentType("image/png");
        try {
            //2.获取响应对象输出流
            OutputStream outputStream = response.getOutputStream();
            //3.使用ImageIO工具类输出
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            //出现异常记录日志：创建日志logger对象
            logger.error("响应验证码失败:"+e.getMessage());
        }
    }

    /**
     * 登陆请求处理
     * @param username
     * @param password
     * @param code 验证码
     * @param remenberme 是否记住密码
     * @param session  将拿到的验证码和之前存入session的验证码比较
     * @param response  登陆成功，下发凭证，凭证保存在cookie，需要使用HttpServletResponse对象携带cookie
     * @param model 封装视图模版数据
     * @return
     */
    @RequestMapping(path="/login",method = RequestMethod.POST)
    public String login(String username,String password,String code,boolean remenberme,
                        HttpSession session,HttpServletResponse response,Model model){

        //检查验证码
        //从session中获取验证码
       String  kaptcha = (String)session.getAttribute("kaptcha");
       //比较验证码
        if(StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            //验证码不对，登陆失败，返回错误信息
            model.addAttribute("codeMsg","验证码不正确");
            return "/site/login";
        }

        //检查账号密码
        //确定登陆凭证过期时间
        int expiredSeconds = remenberme ? REMENBER_EXPIRED_SECOND:DEFAULT_EXPIRED_SECOND;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        //根据登陆的情况不同返回不同的数据
        //如果含有ticket则登陆成功
        if(map.containsKey("ticket")){
            //登陆成功，将凭证放入cookie返回给浏览器
            //创建cookie对象，并封装ticket
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            //设置cookie的范围:为整个项目
            cookie.setPath(contextPath);
            //设置有效时间
            cookie.setMaxAge(expiredSeconds);
            //将cookie发送给客户端，使用response携带发送
            response.addCookie(cookie);

            return "redirect:/index";
        }else{
            //登陆失败，返回错误信息
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "/site/login";
        }

    }

    @RequestMapping(path="/logout",method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket){
        //从cooike中获得ticket,调用service层，根据ticket修改登陆凭证状态
        userService.logout(ticket);
        return "redirect:/login";
    }
}

